﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using XQ.WeChatOfficialAccount.DAL.DAL.Common;

namespace XQ.WeChatOfficialAccount.BLL.Common
{
    public class WxLoginHelper
    {
        /// <summary>
        /// 根据Code获取微信openid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetOpenid(string code)
        {
            string _openid = string.Empty;
            string AppID = ConfigurationManager.AppSettings["AppID"];
            string AppSecret = ConfigurationManager.AppSettings["AppSecret"];
            string _posdata = "appid=" + AppID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
            string _url = "https://api.weixin.qq.com/sns/jscode2session";//获取openid
            string _data = HttpHelper.HttpPostRequest(_url, _posdata);
            if (_data.Contains("\"openid\""))
            {
                dynamic _modal = Newtonsoft.Json.Linq.JToken.Parse(_data) as dynamic;
                _openid = _modal.openid;                
            }
            return _openid;
        }

        public static JObject GetPhone(string code, string iv, string encryptedData)
        {
            LogBll.Instance.WriteLog(LogBll.LogType.LogIn, "", 0, "微信授权获取openid和电话号码", "", "", "", "code:" + code + "|iv:" + iv + "|encrytedData:" + encryptedData);
            JObject jo = new JObject();
            string AppID = ConfigurationManager.AppSettings["AppID"];
            string AppSecret = ConfigurationManager.AppSettings["AppSecret"];
            string _posdata = "appid=" + AppID + "&secret=" + AppSecret + "&js_code=" + code + "&grant_type=authorization_code";
            string _url = "https://api.weixin.qq.com/sns/jscode2session";//获取openid
            string _data = HttpHelper.HttpPostRequest(_url, _posdata);
            if (_data.Contains("\"openid\""))
            {
                dynamic _modal = Newtonsoft.Json.Linq.JToken.Parse(_data) as dynamic;
                string _openid = _modal.openid;
                string _session_key = _modal.session_key;
                if (!string.IsNullOrEmpty(encryptedData) && !string.IsNullOrEmpty(iv))
                {
                    //解析手机号码
                    jo = decodeUser(iv, _session_key, encryptedData);
                    //添加openid
                    jo["openid"] = _openid;

                    LogBll.Instance.WriteLog(LogBll.LogType.Other, "", 0, "解析openid和电话号码", "", "", "", "jo:" + JsonConvert.SerializeObject(jo));
                }
            }
            else
            {
                jo["code"] = "500";
                jo["msg"] = _data;
            }
            //if (!string.IsNullOrEmpty(encryptedData) && !string.IsNullOrEmpty(iv))
            //{
            //    //解析手机号码
            //    jo = decodeUser(iv, session_key, encryptedData);
            //}
            return jo;
        }

        public static JObject decodeUser(string AesIV, string session_key, string inputdata)
        {
            JObject jo = new JObject();
            try
            {
                AesIV = AesIV.Replace(" ", "+");
                session_key = session_key.Replace(" ", "+");
                inputdata = inputdata.Replace(" ", "+");
                byte[] encryptedData = Convert.FromBase64String(inputdata);

                RijndaelManaged rijndaelCipher = new RijndaelManaged();
                rijndaelCipher.Key = Convert.FromBase64String(session_key);// Encoding.UTF8.GetBytes(session_key);
                rijndaelCipher.IV = Convert.FromBase64String(AesIV);// Encoding.UTF8.GetBytes(AesIV);
                rijndaelCipher.Mode = CipherMode.CBC;
                rijndaelCipher.Padding = PaddingMode.PKCS7;
                ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
                byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                string result = Encoding.UTF8.GetString(plainText);
                jo = JsonConvert.DeserializeObject<JObject>(result);
                jo["code"] = "200";
            }
            catch (Exception e)
            {
                jo["code"] = "500";
                jo["msg"] = e.Message;
            }
            return jo;
        }
    }
}
